//
//  BaseViewController.m
//  IOSBase
//
//  Created by chenliang on 14-8-8.
//  Copyright (c) 2014年 chenliang. All rights reserved.
//

#import "BaseViewController.h"
#import "MBProgressHUD.h"
#import <CommonCrypto/CommonDigest.h>
#import "MJRefresh.h"

@interface BaseViewController ()<MJRefreshBaseViewDelegate>
{
    MBProgressHUD *HUD;
    
    MJRefreshHeaderView *_header;

}
@end

@implementation BaseViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    WIDTH = self.view.frame.size.width;
    //减去NavBar没有计算的64
    HEIGHT = self.view.frame.size.height - 64;
    
    //适配IOS6和IOS7的顶点计算方式
    if (self.navigationController != nil && [self isIOS7]) {
//        self.edgesForExtendedLayout = UIRectEdgeNone;
         self.edgesForExtendedLayout = UIRectEdgeBottom;
        //视图控制器，四条边不指定
        self.extendedLayoutIncludesOpaqueBars = NO;
        //不透明的操作栏
        self.modalPresentationCapturesStatusBarAppearance = NO;
    }
    
//        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:NO];
    
    
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    self.navigationController.navigationBar.barTintColor = NAVCOLOR;
    
    self.navigationController.navigationBar.tintColor  = [UIColor whiteColor];
    
    //Universal
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{ NSForegroundColorAttributeName: [UIColor whiteColor],
        NSFontAttributeName:[UIFont boldSystemFontOfSize:20]}];
    

    

}




-(BOOL) isIOS7{
    
    static NSUInteger _deviceSystemMajorVersion = -1;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,^{
        _deviceSystemMajorVersion = [[[[[UIDevice currentDevice] systemVersion] componentsSeparatedByString:@"."] objectAtIndex:0] intValue];
    });
    return (_deviceSystemMajorVersion >= 7);
}

-(BOOL) isiPhone5{
    
    return ([[UIScreen mainScreen] bounds].size.height == 568);
}

- (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

-(void)setNavigationBarImage:(NSString *)image{
   
    if (![self isIOS7]) {
        [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[UIColor orangeColor] size:CGSizeMake(1, 44)] forBarMetrics:UIBarMetricsDefault];
    }
    else
    {
     [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:image] forBarMetrics:UIBarMetricsDefault];
    }
    
    //如果有和NavigationController一起使用，则会产生冲突，这里注释这句代码
//    self.navigationController.navigationBar.translucent = YES;
}

-(void)setNavRightButton:(NSString*)title selecter:(SEL)sel{
    UIBarButtonItem *refreshButton = [[UIBarButtonItem alloc] initWithTitle:title
                                                                    style:UIBarButtonItemStylePlain
                                                                   target:self
                                                                   action:sel];
    if (![self isIOS7]) {
        [refreshButton setTitleTextAttributes:
         @{ NSFontAttributeName: [UIFont systemFontOfSize:14]} forState:UIControlStateNormal];
    }
    self.navigationItem.rightBarButtonItem = refreshButton;

}

-(void)setNavLeftButton:(NSString*)title selecter:(SEL)sel{
    UIBarButtonItem *refreshButton = [[UIBarButtonItem alloc] initWithTitle:title
                                                                      style:UIBarButtonItemStylePlain
                                                                     target:self
                                                                     action:sel];
    if (![self isIOS7]) {
        [refreshButton setTitleTextAttributes:
         @{ NSFontAttributeName: [UIFont systemFontOfSize:14]} forState:UIControlStateNormal];
    }
    self.navigationItem.leftBarButtonItem = refreshButton;
    
}

-(void)hideNavRightButton{
    self.navigationItem.rightBarButtonItem = nil;
}

-(void)hideNavLeftButton{
    self.navigationItem.leftBarButtonItem = nil;
}

-(void)setBackButton{
    
    UIBarButtonItem* backItem = [[UIBarButtonItem alloc] init];
    backItem.title = @"返回";
    self.navigationItem.backBarButtonItem = backItem;
}


#pragma mark -返回按钮点击事件
-(void)clickBack:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)setTitle:(NSString *)title{
    self.navigationItem.title = title;
}


-(void)pushTab:(NSString*)controller{
    self.hidesBottomBarWhenPushed = YES;
    [self push:controller];
    self.hidesBottomBarWhenPushed = NO;
}

-(void)pushTab2:(NSString*)controller{
    self.hidesBottomBarWhenPushed = YES;
    [self push:controller];
}

-(void)pushTab3:(NSString*)controller{
    self.hidesBottomBarWhenPushed = YES;
    self.navigationController.navigationBarHidden = YES;
    [self push:controller];
    self.hidesBottomBarWhenPushed = NO;
}

-(void)pushTab4:(NSString *)controller
{
    self.hidesBottomBarWhenPushed = YES;
    [self setBackButton];
    BaseViewController* vc = [self.storyboard instantiateViewControllerWithIdentifier:controller];
    vc.delegateUpdate = self;
    [self.navigationController pushViewController:vc animated:NO];
}

-(void)pushTabController:(UIViewController*)controller{
    self.hidesBottomBarWhenPushed = YES;
    [self setBackButton];
    [self.navigationController pushViewController:controller animated:NO];
    self.hidesBottomBarWhenPushed = NO;
}

-(void)push:(NSString*)controller{
    [self setBackButton];
    UIViewController* vc = [self.storyboard instantiateViewControllerWithIdentifier:controller];
    [self.navigationController pushViewController:vc animated:NO];
}

-(void)pop{
    [self.navigationController popViewControllerAnimated:NO];
}
-(void)pop3{
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController popViewControllerAnimated:NO];
}

-(void)popRoot{
    [self.navigationController popToRootViewControllerAnimated:NO];
}

-(void)present:(NSString*)controller{
    UIViewController* vc = [self.storyboard instantiateViewControllerWithIdentifier:controller];
    [self presentViewController:vc animated:NO completion:nil];
}

-(void)dismissController{
    [self dismissViewControllerAnimated:NO completion:nil];
}

-(void)showProgressHUD{
    [self showProgressHUD:@"正在加载数据..."];
}

-(void)showProgressHUD:(NSString *)message{
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
	HUD.labelText = message;
    HUD.labelFont = [UIFont systemFontOfSize:12];;
    [HUD show:YES];
}

-(void)hideProgressHUD{
    [HUD removeFromSuperview];
    HUD = nil;
}

-(void)showProgressHUD:(UIView *)view message:(NSString *)message{
    HUD = [MBProgressHUD showHUDAddedTo:view animated:YES];
    HUD.labelText = message;
    HUD.labelFont = [UIFont systemFontOfSize:12];
}

-(void)hideProgressHUDForView:(UIView *)view{
    [MBProgressHUD hideAllHUDsForView:view animated:YES];
}

-(void)showErrorHUD:(NSString *)message{
    MBProgressHUD * errorHud = [[MBProgressHUD alloc] initWithView:self.view];
	[self.view addSubview:errorHud];
    errorHud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error@2x.png"]];
	errorHud.mode = MBProgressHUDModeCustomView;
	errorHud.labelFont = [UIFont systemFontOfSize:12];
	errorHud.labelText = message;
    [errorHud show:YES];
	[errorHud hide:YES afterDelay:2];
}

-(void)showMessageHUD:(NSString *)message{
    
    MBProgressHUD * errorHud = [[MBProgressHUD alloc] initWithView:self.view];
	[self.view addSubview:errorHud];
	errorHud.mode = MBProgressHUDModeCustomView;
	errorHud.labelText = message;
    errorHud.labelFont = [UIFont systemFontOfSize:12];
	[errorHud show:YES];
	[errorHud hide:YES afterDelay:2];
}

-(void)sendASI:(NSString*)url params:(NSDictionary*)params success:(void(^)(NSDictionary *dic)) success failure:(void(^)(NSError *error))failure{
    if(params != nil){
        NSArray * keys = [params allKeys];
        int i = 0;
        for(NSString *key in keys){
            NSString *value = [params objectForKey:key];
            if(i!= 0){
                url = [url stringByAppendingString:@"&"];
            }else{
                url = [url stringByAppendingString:@"?"];
            }
            url = [url stringByAppendingString:[NSString stringWithFormat:@"%@=%@",key,value]];
            i++;
        }
    }
    url=[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    DLog(@"请求URL:%@",url);
    NSURL *URL = [NSURL URLWithString:url];
    
    __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:URL];
    [request setCompletionBlock:^{        
        // Use when fetching binary data
        NSData* responseData = [request responseData];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
        DLog(@"返回数据：%@",dic);
        if(dic != nil){
            int code = [[dic objectForKey:@"code"] intValue];
            NSString * message = [dic objectForKey:@"message"];
            //code=1 成功   code=0失败 code=-1登陆失效
            if(code == 1){
                success(dic);
            }
            else{
                [self hideProgressHUD];
                DLog(@"Base code:%d  message:%@",code,message);
                //登陆失效或超时需清空登录状态
                if (code == -1) {
                    [self reLoginRefresh];
                }
                if (code == 0 || code == -2) {
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil];
                    [alertView show];
                }
                success(dic);
            }

        }else{
            [self hideProgressHUD];            
            failure([request error]);
        }
    }];
    [request setFailedBlock:^{
        [self hideProgressHUD];
        failure([request error]);
    }];
    [request startAsynchronous];
}


-(void)send:(NSString*)url params:(NSDictionary*)params success:(void (^)(id responseObject))success
    failure:(void (^)(NSError *error))failure{
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        success(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        failure(error);
    }];
}

-(void)send:(NSString*)url params:(NSDictionary*)params success:(void (^)(id responseObject))success{
    [self send:url params:params hudMessage:@"正在获取数据..." success:success];
}

-(void)send:(NSString*)url params:(NSDictionary*)params hudMessage:(NSString*)message success:(void (^)(id responseObject))success{
    DLog(@"url:%@",url);
    [self showProgressHUD:message];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject){
        [self hideProgressHUD];
        DLog(@"sucess message:%@",message);
        success(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hideProgressHUD];
        DLog(@"ERROR:%@",error);
        [self showMessageHUD:@"网络连接错误..."];
    }];
}

-(void)reFrameView:(UIView*)view x:(CGFloat)x y:(CGFloat)y width:(CGFloat)width height:(CGFloat)height{

    if(x == -1){
        x = view.frame.origin.x;
    }
    if(y == -1){
        y = view.frame.origin.y;
    }
    if(width == -1){
        width = view.frame.size.width;
    }
    if(height == -1){
        height = view.frame.size.height;
    }
    view.frame = CGRectMake(x, y, width, height);
}

-(void)cornerView:(UIView*)view{
    view.layer.cornerRadius = 3;
    view.layer.masksToBounds = YES;
}

-(UIImage*)resizeImage:(UIImage*)image{
    return [image resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10) resizingMode:UIImageResizingModeStretch];
}


-(void) adapterCellColor:(UITableViewCell*)cell{
    cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
    cell.selectedBackgroundView.backgroundColor = [UIColor lightGrayColor];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//自己实现登陆失效后的页面刷新
-(void)reLoginRefresh{
    
}

//利用正则表达式验证－中文用户名
-(BOOL)isValidateChinese:(NSString *)name {
    NSString *nameRegex = @"^[\\u4E00-\\u9FA5\\uF900-\\uFA2D]+$";
    NSPredicate *nameTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", nameRegex];
    
    return [nameTest evaluateWithObject:name];
}

//利用正则表达式验证－邮箱
-(BOOL)isValidateEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

//利用正则表达式验证－手机号
- (BOOL)isValidateMobile:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,183,184,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,181,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[0-9]|7[0-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,183,184,187,188,17[0-9]
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[23478]|7[0-9])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186,17[0-9]
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56]|7[0-9])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,181,189,17[0-9]
     22         */
    NSString * CT = @"^1((33|53|8[019]|7[0-9])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

-(NSString *)createMD5:(NSString *)signString
{
    const char *cStr = [signString UTF8String];
    unsigned char digest[16];
    CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return  output;
}

-(BOOL)isValidateIDCardNumber:(NSString *)value {
    value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    int length =0;
    if (!value) {
        return NO;
    }else {
        length = (int)value.length;
        
        if (length !=15 && length !=18){
            return NO;
        }
    }
    //省份代码
    NSArray *areasArray =@[@"11",@"12", @"13",@"14", @"15",@"21", @"22",@"23", @"31",@"32", @"33",@"34", @"35",@"36", @"37",@"41", @"42",@"43", @"44",@"45", @"46",@"50", @"51",@"52", @"53",@"54", @"61",@"62", @"63",@"64", @"65",@"71", @"81",@"82", @"91"];
    
    NSString *valueStart2 = [value substringToIndex:2];
    BOOL areaFlag =NO;
    for (NSString *areaCode in areasArray) {
        if ([areaCode isEqualToString:valueStart2]) {
            areaFlag =YES;
            break;
        }
    }
    
    if (!areaFlag) {
        return false;
    }
    
    
    NSRegularExpression *regularExpression;
    NSUInteger numberofMatch;
    
    int year =0;
    switch (length) {
        case 15:
            year = [value substringWithRange:NSMakeRange(6,2)].intValue +1900;
            
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$"
                    options:NSRegularExpressionCaseInsensitive
                    error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$"
                    options:NSRegularExpressionCaseInsensitive
                    error:nil];//测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:value
                               options:NSMatchingReportProgress
                               range:NSMakeRange(0, value.length)];
            
            
            if(numberofMatch >0) {
                return YES;
            }else {
                return NO;
            }
        case 18:
            
            year = [value substringWithRange:NSMakeRange(6,4)].intValue;
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$"  options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$" options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:value
             options:NSMatchingReportProgress  range:NSMakeRange(0, value.length)];
        
            
            if(numberofMatch > 0) {
                int S = ([value substringWithRange:NSMakeRange(0,1)].intValue + [value substringWithRange:NSMakeRange(10,1)].intValue) *7 + ([value substringWithRange:NSMakeRange(1,1)].intValue + [value substringWithRange:NSMakeRange(11,1)].intValue) *9 + ([value substringWithRange:NSMakeRange(2,1)].intValue + [value substringWithRange:NSMakeRange(12,1)].intValue) *10 + ([value substringWithRange:NSMakeRange(3,1)].intValue + [value substringWithRange:NSMakeRange(13,1)].intValue) *5 + ([value substringWithRange:NSMakeRange(4,1)].intValue + [value substringWithRange:NSMakeRange(14,1)].intValue) *8 + ([value substringWithRange:NSMakeRange(5,1)].intValue + [value substringWithRange:NSMakeRange(15,1)].intValue) *4 + ([value substringWithRange:NSMakeRange(6,1)].intValue + [value substringWithRange:NSMakeRange(16,1)].intValue) *2 + [value substringWithRange:NSMakeRange(7,1)].intValue *1 + [value substringWithRange:NSMakeRange(8,1)].intValue *6 + [value substringWithRange:NSMakeRange(9,1)].intValue *3;
                int Y = S %11;
                NSString *M =@"F";
                NSString *JYM =@"10X98765432";
                M = [JYM substringWithRange:NSMakeRange(Y,1)];//判断校验位
                if ([M isEqualToString:[value substringWithRange:NSMakeRange(17,1)]]) {
                    return YES;// 检测ID的校验位
                }else {
                    return NO;
                }
                
            }else {
                return NO;
            }
        default:
            return false;
    }
}

@end
